<template>
  <div class="goods-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索电影ID/名称/类型"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增电影
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredMovies" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="movieId" label="电影ID" width="180" sortable align="center" />
      <el-table-column prop="name" label="电影名称" width="180" />
      <el-table-column prop="director" label="导演" width="160" />
      <el-table-column prop="genre" label="类型" width="150">
        <template #default="{ row }">
          <el-tag effect="plain" :type="genreTagType[row.genre]">
            {{ row.genre }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="票价" width="150" align="center">
        <template #default="{ row }">
          <span style="color: #e74c3c;">¥{{ row.price.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="上映状态" width="160" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]" effect="light">
            {{ statusMap[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="releaseDate" label="上映日期" width="180" sortable />
      <el-table-column prop="description" label="剧情简介" width="280">
        <template #default="{ row }">
          <div class="content-preview">{{ row.description }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.movieId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑电影信息' : '新增电影'"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="500px"
        label-position="left"
      >
        <el-form-item label="电影ID" prop="movieId">
          <el-input 
            v-model="formData.movieId" 
            :disabled="isEditMode"
            placeholder="请输入电影ID（如：MV2024001）"
          />
        </el-form-item>
        <el-form-item label="电影名称" prop="name">
          <el-input 
            v-model="formData.name"
            placeholder="请输入电影全称"
          />
        </el-form-item>
        <el-form-item label="导演" prop="director">
          <el-input 
            v-model="formData.director"
            placeholder="请输入导演"
          />
        </el-form-item>
        <el-form-item label="类型" prop="genre">
          <el-select 
            v-model="formData.genre"
            placeholder="请选择类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in genres"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="票价" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :step="5"
            controls-position="right"
            style="width: 100%"
            :precision="2"
            placeholder="请输入票价"
          >
            <template #prefix>¥</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="上映状态" prop="status">
          <el-select 
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上映日期" prop="releaseDate">
          <el-date-picker
            v-model="formData.releaseDate"
            type="date"
            placeholder="选择上映日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="剧情简介" prop="description">
          <el-input 
            type="textarea"
            v-model="formData.description" 
            rows="4"
            placeholder="请输入剧情简介"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 类型配置
const genres = [
  '剧情',
  '科幻',
  '爱情',
  '动作',
  '喜剧',
  '悬疑'
]

// 状态配置
const statusOptions = [
  { value: 0, label: '热映中' },
  { value: 1, label: '即将上映' },
  { value: 2, label: '已下映' }
]

// 标签样式映射
const genreTagType = {
  '剧情': 'info',
  '科幻': 'warning',
  '爱情': 'danger',
  '动作': 'success',
  '喜剧': 'primary',
  '悬疑': ''
}

const statusTagType = {
  0: 'success',
  1: 'warning',
  2: 'danger'
}

const statusMap = {
  0: '热映',
  1: '待映',
  2: '下映'
}

// 电影数据（10条）
const moviesList = ref([
  {
    movieId: 'MV2024001',
    name: '肖申克的救赎',
    director: '弗兰克·德拉邦特',
    genre: '剧情',
    price: 45.90,
    status: 0,
    releaseDate: '2024-05-20',
    description: '经典越狱题材电影，讲述银行家安迪的监狱救赎之旅'
  },
  {
    movieId: 'MV2024002',
    name: '流浪地球2',
    director: '郭帆',
    genre: '科幻',
    price: 59.00,
    status: 0,
    releaseDate: '2024-01-22',
    description: '中国科幻巨制，展现人类推动地球逃离太阳系的壮举'
  },
  {
    movieId: 'MV2024003',
    name: '泰坦尼克号',
    director: '詹姆斯·卡梅隆',
    genre: '爱情',
    price: 49.90,
    status: 2,
    releaseDate: '2023-12-10',
    description: '经典爱情灾难片，重现1912年豪华邮轮沉没事件'
  },
  {
    movieId: 'MV2024004',
    name: '速度与激情10',
    director: '路易斯·莱特里尔',
    genre: '动作',
    price: 65.00,
    status: 1,
    releaseDate: '2024-06-15',
    description: '飙车家族最终章，上演全球追捕与终极对决'
  },
  {
    movieId: 'MV2024005',
    name: '人生大事',
    director: '刘江江',
    genre: '剧情',
    price: 39.90,
    status: 0,
    releaseDate: '2024-04-05',
    description: '殡葬师莫三妹与孤儿武小文互相治愈的温情故事'
  },
  {
    movieId: 'MV2024006',
    name: '独行月球',
    director: '张吃鱼',
    genre: '喜剧',
    price: 45.00,
    status: 2,
    releaseDate: '2023-11-18',
    description: '科幻喜剧，讲述被遗落月球的维修工生存历险'
  },
  {
    movieId: 'MV2024007',
    name: '消失的她',
    director: '崔睿',
    genre: '悬疑',
    price: 55.00,
    status: 0,
    releaseDate: '2024-05-12',
    description: '夫妻异国寻妻悬疑故事，多重反转烧脑剧情'
  },
  {
    movieId: 'MV2024008',
    name: '长津湖之水门桥',
    director: '徐克',
    genre: '战争',
    price: 42.50,
    status: 2,
    releaseDate: '2023-10-01',
    description: '抗美援朝战争片，展现水门桥战役的惨烈与英勇'
  },
  {
    movieId: 'MV2024009',
    name: '这个杀手不太冷静',
    director: '邢文雄',
    genre: '喜剧',
    price: 38.00,
    status: 1,
    releaseDate: '2024-07-20',
    description: '爆笑喜剧，龙套演员意外卷入黑帮阴谋'
  },
  {
    movieId: 'MV2024010',
    name: '悬崖之上',
    director: '张艺谋',
    genre: '剧情',
    price: 43.90,
    status: 2,
    releaseDate: '2023-09-15',
    description: '谍战悬疑片，讲述特工小组执行秘密任务的故事'
  },
  {
    movieId: 'MV2024008',
    name: '长津湖之水门桥',
    director: '徐克',
    genre: '战争',
    price: 42.50,
    status: 2,
    releaseDate: '2023-10-01',
    description: '抗美援朝战争片，展现水门桥战役的惨烈与英勇'
  },
  {
    movieId: 'MV2024009',
    name: '这个杀手不太冷静',
    director: '邢文雄',
    genre: '喜剧',
    price: 38.00,
    status: 1,
    releaseDate: '2024-07-20',
    description: '爆笑喜剧，龙套演员意外卷入黑帮阴谋'
  },
  {
    movieId: 'MV2024010',
    name: '悬崖之上',
    director: '张艺谋',
    genre: '剧情',
    price: 43.90,
    status: 2,
    releaseDate: '2023-09-15',
    description: '谍战悬疑片，讲述特工小组执行秘密任务的故事'
  }
])

// 搜索功能
const searchText = ref('')
const filteredMovies = computed(() => {
  const search = searchText.value.toLowerCase()
  return moviesList.value.filter(movie => 
    movie.movieId.toLowerCase().includes(search) ||
    movie.name.toLowerCase().includes(search) ||
    movie.director.toLowerCase().includes(search) ||
    movie.genre.toLowerCase().includes(search)
  )
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  movieId: '',
  name: '',
  director: '',
  genre: '剧情',
  price: 0,
  status: 0,
  releaseDate: new Date().toISOString().split('T')[0],
  description: ''
})

// 表单验证规则
const formRules = {
  movieId: [
    { required: true, message: '电影ID不能为空', trigger: 'blur' },
    { pattern: /^MV\d{7}$/, message: '格式：MV+7位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入电影名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入票价', trigger: 'blur' },
    { type: 'number', min: 0, max: 999, message: '票价范围0-999元', trigger: 'blur' }
  ],
  genre: { required: true, message: '请选择类型', trigger: 'change' }
}

// 处理添加
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (movieId) => {
  ElMessageBox.confirm('确定要删除该电影？', '警告', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    moviesList.value = moviesList.value.filter(m => m.movieId !== movieId)
    ElMessage.success('电影删除成功')
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = moviesList.value.findIndex(m => m.movieId === formData.movieId)
    moviesList.value.splice(index, 1, { ...formData })
  } else {
    if (moviesList.value.some(m => m.movieId === formData.movieId)) {
      return ElMessage.warning('电影ID已存在')
    }
    moviesList.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '更新成功' : '新增成功')
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    movieId: '',
    name: '',
    director: '',
    genre: '剧情',
    price: 0,
    status: 0,
    releaseDate: new Date().toISOString().split('T')[0],
    description: ''
  })
}
</script>

<style scoped lang="scss">
.goods-management {
  padding: 24px;
  background: #1a1a2e;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: rgba(40,40,60,0.9);
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(231,76,60,0.2);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #2c3e50 !important;
    color: #e6e6e6;
    font-weight: 600;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(231,76,60,0.2);
    background: rgba(40,40,60,0.95);
    
    .el-tag {
      font-size: 13px;
      padding: 0 8px;
      height: 26px;
      line-height: 24px;
    }
  }

  .content-preview {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
    color: #bdc3c7;
  }
}

.el-dialog {
  border-radius: 12px;
  background: #2c3e50;
  
  .el-dialog__header {
    border-bottom: 1px solid #e74c3c;
    margin: 0 24px;
    padding: 24px 0 16px;
    color: #ffffff;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
    color: #ecf0f1;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #e74c3c;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
  :deep(.el-form-item__label) {
    color: #ecf0f1;
  }
}
</style>